<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="courseid">
        <el-input
          v-model="queryParams.courseid"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:videos:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:videos:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:videos:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程id" align="center" prop="courseid" />
      <el-table-column label="课程名称" align="center">
        <template slot-scope="scope">
          <span>{{ getCourseName(scope.row.courseid) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程url" align="center" prop="videourl" />
      <el-table-column label="创建时间" align="center" prop="createtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:videos:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:videos:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 新增 -->
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="选择课程">
          <!-- v-infinite-scroll=""  -->
          <ul v-if="selectCourse===null" class="infinite-list" style="overflow:auto; height:100px; margin-top:0px; padding-top:0px;">
              <li v-for="item in coursesList" class="infinite-list-item" @click="clickItem(item)">{{ item.coursename }}</li>
          </ul>
          <div v-else>
            <span >{{selectCourse}}</span> <el-button type="primary" size="mini" @click="reSelect">重选</el-button>  
          </div>
        </el-form-item>
        <el-form-item :label="'视频课程'+(index+1)" v-for="(input, index) in inputs" :key="index">
          <el-input  v-model="input.value" :placeholder="`例: https://www.xxx.com/课程`+(index+1)+`.mp4`" @input="handleInput(index, $event)" style="width:320px;" />
          <i class="el-icon-remove" style="font-size:22px; color:red; margin-left:10px; cursor: pointer;" @click="delitem(index)"></i>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVideoUrl">+添加视频课程</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVideos, getVideos, delVideos, addVideos, updateVideos,getCourseVideosList } from "@/api/system/videos";
import { listCourses } from "@/api/system/courses";
export default {
  name: "Videos",
  data() {
    return {
      count: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      videosList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 视频查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseid: null,
        videourl: null,
        createtime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseid: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        videourl:[
          { required: true, message: "视频地址不能为空", trigger: "blur" }
        ]
      },
      inputIds:[], //要更新的课程id集合，和inputs一一对应
      inputs: [
        // { value: '' },
        // { value: '' },
        // { value: '' },
        // 可以根据需要添加更多的inputs
      ],
      coursesList: [], //课程列表
      // 课程查询参数
      coursesQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      selectCourseId:null, //选择的课程id
      selectCourse:null, //选择的课程
      isUpdate:false,
    };
  },
  created() {
    this.getList();
    this.getCoursesList(); //获取课程信息
    for(let i=0;i<3;i++){
      let obj={};
      obj.value='';
      this.inputs.push(obj);
    }
  },
  methods: {
    getCourseName(courseid){
        let index=this.coursesList.findIndex(item=>item.id===courseid);
        if(index!=-1){
          return this.coursesList[index].coursename;
        }else{
          return "";
        }
    },
    delitem(index){
      console.log("删除索引",index,this.inputs);
      this.inputs.splice(index,1);
    },
    addVideoUrl(){
      let obj={};
      obj.value='';
      this.inputs.push(obj);
    },
    reSelect(){
      this.selectCourse=null;
    },
    handleInput(index, event) {
      // 更新inputs数组中对应索引的值
      console.log("索引"+index+"值:",this.inputs[index].value) ;
    },
    inputsMerge(){
      let str="";
      for(let i=0;i<this.inputs.length;i++){
          if(this.inputs[i].value!=""){
            str+=this.inputs[i].value+",";
          }   
      }
      return str.substring(0,str.length-1);
    },
    idsMerge(){
      let str="";
      for(let i=0;i<this.inputIds.length;i++){
          if(this.inputIds[i]!=""){
            str+=this.inputIds[i]+",";
          }   
      }
      return str.substring(0,str.length-1);
    },
    // load(){
    //     this.count += 2
    // },
    clickItem(item){
       //console.log(courseName); 
       this.selectCourseId=item.id;
       this.selectCourse=item.coursename;
       console.log("选择的课程id：",this.selectCourseId,"课程名称:",this.selectCourse);
    },
    /** 查询【课程】列表 */
    getCoursesList() {
      this.loading = true;
      listCourses(this.coursesQueryParams).then(response => {
        console.log("课程信息返回:",response);
        this.coursesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询【视频】列表 */
    getList() {
      this.loading = true;
      listVideos(this.queryParams).then(response => {
        this.videosList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.selectCourse=null;
      this.inputs=[];
      for(let i=0;i<3;i++){
        let obj={};
        obj.value='';
        this.inputs.push(obj);
      }
      this.form = {
        id: null,
        courseid: null,
        videourl: null,
        createtime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isUpdate=false;
      this.open = true;
      this.title = "添加【课程视频】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset(); 
      //console.log(row);
      this.isUpdate=true;
      const courseid = row.courseid
      getCourseVideosList(courseid).then(response => {
        console.log("获取修改数据",response);
        this.inputIds=[];
        this.inputs=[];
        this.selectCourseId=courseid;
        this.selectCourse=this.getCourseName(response.rows[0].courseid);
        response.rows.forEach(item => {
          let obj={}
          obj.value=item.videourl;
          this.inputs.push(obj);
          this.inputIds.push(item.id);
        });
        this.open = true;
        this.title = "修改【课程视频】";
      })
      // getVideos(id).then(response => {
      //   console.log("获取修改数据",response);
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改【课程视频】";
      // });
    },
    /** 提交按钮 */
    submitForm() {

      if(this.selectCourseId===null || this.selectCourse===null){
        this.$alert('选择相应的课程', '请选择课程');
        return;
      }

      //合并课程视频地址
      if(this.isUpdate){
        this.form.id=this.idsMerge();
      }
      this.form.courseid=this.selectCourseId;
      this.form.videourl=this.inputsMerge();
      console.log("提交的form参数:",this.form);  

      if(this.form.videourl===""){
        this.$alert('最少填写一个课程网络视频地址', '填写视频课程地址');
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVideos(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideos(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【课程视频】编号为"' + ids + '"的数据项？').then(function() {
        return delVideos(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/videos/export', {
        ...this.queryParams
      }, `videos_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
